package com.source.hotelbath.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.content.LocalBroadcastManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.source.hotelbath.R;
import com.source.hotelbath.base.BizActivity;
import com.source.hotelbath.net.CustomerRequestConstants;
import com.source.hotelbath.net.response.HotelListResponse;
import com.source.hotelbath.utils.SharedPreferencesUtils;
import com.source.hotelbath.utils.hotel.CharacterParser;
import com.source.hotelbath.utils.hotel.PinyinComparator;
import com.source.hotelbath.utils.hotel.SideBar;
import com.source.hotelbath.utils.hotel.SortAdapter;
import com.source.hotelbath.utils.hotel.SortModel;
import com.source.hotelbath.utils.hotel.SortToken;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;

public class HotelSelectAct extends BizActivity {

    ListView mListView;
    EditText etSearch;
    ImageView ivClearText;

    private SideBar sideBar;
    private TextView dialog;

    private List<SortModel> SourceDateList;
    private SortAdapter adapter;
    /** 汉字转换成拼音的类 */
    private CharacterParser characterParser;

    /** 根据拼音来排列ListView里面的数据类 */
    private PinyinComparator pinyinComparator;
    private LinearLayout ll_header_left;
    private  LinearLayout ll_header_right;
    private HotelListResponse hotelListResponse;
    private int selectId;
    private boolean isClick;
    private int hotelId;
    private String hotelName;
    private String tag;

    @Override
    protected void onBaseCreate(Bundle var1) {
        setContentView(R.layout.activity_hotel_select);
    }

    @Override
    protected void bindView(Bundle var1) {
        tag = getIntent().getStringExtra("TAG");
        ll_header_left = (LinearLayout) findViewById(R.id.ll_header_left);

        ll_header_right = (LinearLayout) findViewById(R.id.ll_header_right);
        TextView tv_header_right= (TextView) findViewById(R.id.tv_header_right);
        tv_header_right.setText("提交");
        ll_header_right.setVisibility(View.VISIBLE);
        ll_header_right.setOnClickListener(this);
        ll_header_left.setOnClickListener(this);
        TextView tv_header_title= (TextView) findViewById(R.id.tv_header_title);
        tv_header_title.setText("选择酒店");
        sideBar = (SideBar) findViewById(R.id.sidrbar);
        dialog = (TextView) findViewById(R.id.dialog);
        sideBar.setTextView(dialog);
        ivClearText = (ImageView) findViewById(R.id.ivClearText);
        etSearch = (EditText) findViewById(R.id.et_search);
        mListView = (ListView) findViewById(R.id.lv_contacts);

        characterParser = CharacterParser.getInstance();
        pinyinComparator = new PinyinComparator();

        initListener();
        initData();
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        if (view==ll_header_left){
            finish();
        }else if (view==ll_header_right){
            if ("OrderFragment".equals(tag)){
                Intent intent = new Intent();
                intent.putExtra("hotelId",hotelId);
                intent.putExtra("hotelName",hotelName);
                setResult(RESULT_OK,intent);

            }else {
                Intent intent = new Intent(CustomerRequestConstants.CHOOSEHOTEL);
                intent.putExtra("hotelId",hotelId);
                intent.putExtra("hotelName",hotelName);
                LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
            }
            finish();

        }
    }

    private void initData() {
        String hotelString= SharedPreferencesUtils.getStringData(this,"hotelList","");
        if (!TextUtils.isEmpty(hotelString)){
            Gson gson = new Gson();
            hotelListResponse=gson.fromJson(hotelString,HotelListResponse.class);
            SourceDateList = filledData(hotelListResponse);
            Collections.sort(SourceDateList, pinyinComparator);
            adapter = new SortAdapter(this, SourceDateList);
            mListView.setAdapter(adapter);
        }

    }




    private List<SortModel> filledData(HotelListResponse date){
        List<SortModel> mSortList = new ArrayList<SortModel>();

        for(int i=0; i<date.getHotelList().size(); i++){
            SortModel sortModel = new SortModel();
            sortModel.setName(date.getHotelList().get(i).getHotelName());
            sortModel.setHotelId(date.getHotelList().get(i).getHotelId());
            String pinyin = characterParser.getSelling(date.getHotelList().get(i).getHotelName());
            String sortString = pinyin.substring(0, 1).toUpperCase();


            if(sortString.matches("[A-Z]")){
                sortModel.setSortLetters(sortString.toUpperCase());
            }else{
                sortModel.setSortLetters("#");
            }

            mSortList.add(sortModel);
        }
        return mSortList;

    }

    private void initListener() {

        /**清除输入字符**/
        ivClearText.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                etSearch.setText("");
            }
        });
        etSearch.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int arg1, int arg2, int arg3) {
                filterData(s.toString());
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {

            }

            @Override
            public void afterTextChanged(Editable e) {


            }

        });

        //设置右侧[A-Z]快速导航栏触摸监听
        sideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {

            @Override
            public void onTouchingLetterChanged(String s) {
                //该字母首次出现的位置
                int position = adapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    mListView.setSelection(position);
                }
            }
        });

        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long arg3) {
//                 ImageView imageView= (ImageView) view.findViewById(R.id.iv_selct);
//                 if (imageView.isSelected()){
//                     imageView.setSelected(false);
//                 }else {
//                     imageView.setSelected(true);
//                 }
                 selectId=position;
                 isClick=true;
                hotelId =SourceDateList.get(position).getHotelId();
                hotelName=SourceDateList.get(position).getName();
                 adapter.add(selectId,isClick);
//                 adapter.notifyDataSetChanged();
            }
        });

    }

    /**
     * 模糊查询
     * @param filterStr
     */
    private void filterData(String filterStr){
        List<SortModel> filterDateList = new ArrayList<SortModel>();

        if(TextUtils.isEmpty(filterStr)){
            filterDateList = SourceDateList;
        }else{
            filterDateList.clear();
            for(SortModel sortModel : SourceDateList){
                String name = sortModel.getName();
                if(name.indexOf(filterStr.toString()) != -1 || characterParser.getSelling(name).startsWith(filterStr.toString())){
                    filterDateList.add(sortModel);
                }
            }
        }

        Collections.sort(filterDateList, pinyinComparator);
        adapter.updateListView(filterDateList);
    }

    /** 中文字符串匹配 */
    String chReg = "[\\u4E00-\\u9FA5]+";

    //String chReg="[^\\u4E00-\\u9FA5]";//除中文外的字符匹配
    /**
     * 解析sort_key,封装简拼,全拼
     * @param sortKey
     * @return
     */
    public SortToken parseSortKey(String sortKey) {
        SortToken token = new SortToken();
        if (sortKey != null && sortKey.length() > 0) {
            //其中包含的中文字符
            String[] enStrs = sortKey.replace(" ", "").split(chReg);
            for (int i = 0, length = enStrs.length; i < length; i++) {
                if (enStrs[i].length() > 0) {
                    //拼接简拼
                    token.simpleSpell += enStrs[i].charAt(0);
                    token.wholeSpell += enStrs[i];
                }
            }
        }
        return token;
    }

}
